package cn.slimsmart.thrift.rpc.demo.client;

import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;

import cn.slimsmart.thrift.rpc.demo.service.EchoSerivce;
import cn.slimsmart.thrift.rpc.demo.service.HelloWorldService;

/**
 * 客户端代理
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class ThriftServiceClientProxyFactory2<T> implements FactoryBean<T> {
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	public static final int TIMEOUT = 30000;
	
	private CuratorFramework zkClient;
	
	private String servicClassName;
	
	private String version;
	
	
	@Override
	public T getObject()  {
		try {
			List<String>list=zkClient.getChildren().forPath("/"+servicClassName+"/"+version);
			for (String string : list) {
				String[] strArr=string.split(":");
				String ip=strArr[0];
				Integer port=Integer.parseInt(strArr[1]);
				String serviceName=strArr[2];
				
				TTransport transport = new TFramedTransport(new TSocket(ip,port, TIMEOUT));
				// 协议要和服务端一致
				TProtocol protocol = new TCompactProtocol(transport);
				transport.open();
				TMultiplexedProtocol mp1 = new TMultiplexedProtocol(protocol,serviceName);
				EchoSerivce.Client client = new EchoSerivce.Client(mp1);
				String result = client.echo("dddd");
				System.out.println("Thrify client result =: " + result);
				transport.close();  
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return null;
	}

	@Override
	public Class getObjectType() {
		return Object.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	/**
	 * @return the zkClient
	 */
	public CuratorFramework getZkClient() {
		return zkClient;
	}

	/**
	 * @param zkClient the zkClient to set
	 */
	public void setZkClient(CuratorFramework zkClient) {
		this.zkClient = zkClient;
	}

	/**
	 * @return the servicClassName
	 */
	public String getServicClassName() {
		return servicClassName;
	}

	/**
	 * @param servicClassName the servicClassName to set
	 */
	public void setServicClassName(String servicClassName) {
		this.servicClassName = servicClassName;
	}

	/**
	 * @return the version
	 */
	public String getVersion() {
		return version;
	}

	/**
	 * @param version the version to set
	 */
	public void setVersion(String version) {
		this.version = version;
	}

	

}
